package com.unicdata.ai.demo_2af.service;

import com.unicdata.ai.demo_2af.common.entity.User;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 2FA 服务类
 *
 * @author lhn
 * @date 2025/06/26 16:43
 * @since 1.0.0
 **/
@Service
@Slf4j
public class TwoFactorService {
    @Autowired
    private GoogleAuthenticator googleAuthenticator;

    @Autowired
    private UserService userService;

    /**
     * 生成2FA密钥和二维码URL
     */
    public Map<String, String> generateTwoFactorSecret(String username) {
        // 生成密钥
        final String secretKey = googleAuthenticator.createCredentials().getKey();
        Map <String, String> result = new HashMap <>();

        try {
            String encodedUsername = URLEncoder.encode(username, StandardCharsets.UTF_8.toString());

            // 生成二维码URL
            String otpAuthURL = String.format(
                    "otpauth://totp/%s?secret=%s&issuer=YourApplication",
                    encodedUsername,
                    secretKey
            );

            result.put("secret", secretKey);
            result.put("otpAuthUrl", otpAuthURL);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        return result;
    }

    /**
     * 验证2FA码
     */
    public boolean validateCode(String secretKey, int code) {
        try {
            return googleAuthenticator.authorize(secretKey, code);
        } catch (Exception e) {
            log.error("2FA验证失败", e);
            return false;
        }
    }

    /**
     * 启用2FA
     */
    public void enableTwoFactor(Long userId, String secretKey) {
        User user = userService.getById(userId);
        if (user != null) {
            user.setTwoFactorSecret(secretKey);
            user.setIsTwoFactorEnabled(1);
            userService.updateById(user);
        }
    }
}